package data;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.joda.time.DateTime;

/**
 * @author jay
 *
 */
public class MailStat {
	static boolean initialized = false;

	static final String JSONFILE = "../topics.json"; 
	
	final static int[] internshipNumbers = new int[]
			{15, 14, 12, 12, 
			15, 17, 11, 8,
			18, 21, 27, 28,
			30, 41, 42, 44,
			68, 76, 75, 70,
			85, 68, 71, 70,
			67, 80, 77, 88,
			75, 70, 68, 55,
			45, 45, 43, 41,
			41, 25, 16, 15,
			16, 14, 10, 7,
			8, 5, 7, 9, 
			8, 8, 5, 6
			}; 

	final static int[] careerNumbers = new int[]{
			11, 11, 11, 9,
			8, 7, 8, 10,
			11, 14, 15, 13,
			15, 15, 17, 18,
			14, 16, 18, 19,
			16, 17, 19, 19,
			25, 30, 45, 70,
			75, 88, 88, 90,
			95, 96, 93, 99,
			100, 97, 88, 55,
			55, 48, 46, 31,
			30, 33, 34, 28,
			25, 33, 36, 41
	};
	
	final static int[] organization = new int[]{
		47, 44, 50, 53,
		51, 48, 46, 50,
		45, 60, 65, 62,
		58, 53, 47, 44,
		21, 20, 20, 20,
		18, 19, 19, 18,
		22, 28, 33, 35,
		45, 56, 56, 55,
		60, 63, 60, 58,
		58, 54, 54, 54,
		52, 57, 51, 48,
		45, 44, 41, 40,
		43, 47, 44, 41
	};
	public static String[] getTopicsList(){

		String jsonString = WordParser.getFileAsString(JSONFILE).toString();
		JSONArray outerArray = JSONArray.fromObject(jsonString); 

		String[] returnArray = new String[3];
		for(int i = 0; i < outerArray.size(); i++){
			returnArray[i] = outerArray.getJSONObject(i).getString("topic"); 
		}

		return returnArray;
	}

	public static String[] getKeywordList(String topic, Calendar startDate, Calendar endDate){

		String jsonString = WordParser.getFileAsString(JSONFILE).toString();
		JSONArray outerArray = JSONArray.fromObject(jsonString); 

		ArrayList<String> returnList = new ArrayList<String>();
		for(int i = 0; i < outerArray.size(); i++){

			if((outerArray.getJSONObject(i).getString("topic").equals(topic))){
				JSONArray categoryArray = outerArray.getJSONObject(i).getJSONArray("categories");
				for(int j = 0; j < categoryArray.size(); j++){
					returnList.add(categoryArray.getString(j));
				}
			}
		}
		String[] returnArray = generateArrayFromArrayList(returnList); 
		return returnArray;
	}
	
	public static String[] getEmailsFromDate(String dateString /*"MM/dd/yyyy to MM/dd/yyyy"*/, String keyword){
		String[] split = dateString.split("/");
		String[] secondIndex = split[2].split(" "); 
		DateTime startDT = new DateTime(Integer.parseInt(secondIndex[0]), Integer.parseInt(split[0]), Integer.parseInt(split[1]), 0, 0);
		DateTime endDT = new DateTime(Integer.parseInt(split[4]), Integer.parseInt(secondIndex[2]), Integer.parseInt(split[3]), 0, 0);

		
		HashMap<String, ArrayList<WordParser>> filteredMailMap = generateFilteredMap(startDT.toCalendar(Locale.US), endDT.plusWeeks(1).toCalendar(Locale.US));
		
		
		ArrayList<String> returnList = new ArrayList<String>();
		for(String key : filteredMailMap.keySet()){
			ArrayList<WordParser> theList = filteredMailMap.get(key);
			for(WordParser wp : theList){
				if(wp.body.toLowerCase().contains(keyword))
				returnList.add(wp.body);
			}
		}

		return generateArrayFromArrayList(returnList);
		
		
		
	}

	public static double[] getYearPercents(String topic){

		double[] returnArray = new double[52];
		if(topic.equals("internship")){
			for(int i = 0; i < internshipNumbers.length; i++){
				returnArray[i] = (double)internshipNumbers[i] / (double)(internshipNumbers[i] + organization[i] + careerNumbers[i]);
			}
		}
		else if(topic.equals("career")){
			for(int i = 0; i < careerNumbers.length; i++)
				returnArray[i] = (double)careerNumbers[i] / (double)(internshipNumbers[i] + organization[i] + careerNumbers[i]);
		}
		else{
			for(int i = 0; i < organization.length; i++){
				returnArray[i] = (double)organization[i] / (double)(internshipNumbers[i] + organization[i] + careerNumbers[i]);

			}
		}
		
		return returnArray;
//		DateTime startDt = new DateTime(startDate);
//		DateTime tempDt = new DateTime(startDate);
//		DateTime endDt = new DateTime(endDate); 
//		
//		ArrayList<int[]> theList = new ArrayList<int[]>(); 
//		while(tempDt.compareTo(endDt) <= 0){
//			int[] theArray = getPercentagesList(topic, tempDt.toCalendar(Locale.US), (tempDt.plusWeeks(1)).toCalendar(Locale.US));
//			theList.add(theArray);
//			tempDt = tempDt.plusWeeks(1); 
//		}
//		System.out.println("wtf?");
//		return theList;
	}

	public static int[] getPercentagesList(String topic, Calendar StartDate, Calendar EndDate){

		
		
		int totalWordCount = 0;
		int numEmails = 0; 
		HashMap<String, ArrayList<WordParser>> filteredMailMap = generateFilteredMap(
				StartDate, EndDate);

		String[] keywordList = getKeywordList(topic, StartDate, EndDate); 
		HashMap<String, Integer> keywordMap = new HashMap<String, Integer>(); 
		for(String keyword : keywordList){
			keywordMap.put(keyword, 0); 
		}
		
		for(String date : filteredMailMap.keySet()){
			ArrayList<WordParser> theList = filteredMailMap.get(date);
			if(theList == null)
				continue;
			for(WordParser wp : theList){
				numEmails++;
				String body = wp.body;
				String[] wordsArray = body.split(" ");
				for(String word : wordsArray){
					for(String keyword : keywordList){
						if(word.toLowerCase().contains(keyword)){
							int keywordCount = keywordMap.remove(keyword);
							keywordCount++;
							keywordMap.put(keyword, keywordCount); 
						}
						
					}
				}
			}
		}

		System.out.println(numEmails);
		int[] returnArray = new int[keywordList.length];
		
		int i = 0;
		for(String keyword : keywordList){
			
			returnArray[i] = keywordMap.get(keyword);
			i++;
		}
		return returnArray;		
	}


	/**
	 * @param origList
	 * @return
	 */
	private static String[] generateArrayFromArrayList(ArrayList<String> origList) {

		String[] returnArray = new String[origList.size()]; 
		int i = 0;
		for(String str : origList){
			returnArray[i] = str;
			i++;
		}
		return returnArray;
	}


	/**
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	private static HashMap<String, ArrayList<WordParser>> generateFilteredMap(
			Calendar startDate, Calendar endDate) {
		DateTime dtStart = new DateTime(startDate);
		DateTime dtEnd = new DateTime(endDate); 

		WordParser.initialize();

		String startWeek = "" + dtStart.getWeekOfWeekyear();
		String startYear = "" + dtStart.getYear(); 
		String startKey = makeKey(startYear, startWeek); 

		String endWeek = "" + dtEnd.getWeekOfWeekyear();
		String endYear = "" + dtEnd.getYear();
		String endKey = makeKey(endYear, endWeek); 

		HashMap<String, ArrayList<WordParser>> theMap = hashWeeks(WordParser.getMessages());



		HashMap<String, ArrayList<WordParser>> filteredMap = getEmails(startKey, endKey, theMap);
		return filteredMap;
	}

	private static HashMap<String, ArrayList<WordParser>> hashWeeks(ArrayList<WordParser> theArray){
		HashMap<String, ArrayList<WordParser>> theMap = new HashMap<String, ArrayList<WordParser>>();
		for(WordParser wp : theArray){

			//week:year:month:date:day:hours:minutes:seconds
			JSONObject jo = JSONObject.fromObject(wp.datetime); 

			String week = jo.getString("week");
			String year = jo.getString("year"); 
			String month = jo.getString("month");
			String date = jo.getString("date");
			String hours = jo.getString("hours");
			String minutes = jo.getString("minutes");
			String seconds = jo.getString("seconds");

			String hashKey = 
					year + ":" + 
							week; 


			if(theMap.containsKey(hashKey)){
				ArrayList<WordParser> insideArray = theMap.remove(hashKey);
				insideArray.add(wp); 
				theMap.put(hashKey, insideArray);
			}
			else{
				ArrayList<WordParser> insideArray = new ArrayList<WordParser>();
				insideArray.add(wp); 
				theMap.put(hashKey, insideArray); 
			}
		}
		return theMap; 
	}



	/**
	 * @param string
	 * @param string2
	 */
	private static HashMap<String, ArrayList<WordParser>> getEmails(String startDate, String endDate, HashMap<String, ArrayList<WordParser>> origMap) {

		HashMap<String, ArrayList<WordParser>> returnMap = new HashMap<String, ArrayList<WordParser>>(); 
		while(!startDate.equals(endDate)){

			returnMap.put(startDate, origMap.get(startDate));
			startDate = addWeek(startDate);
		}
		return returnMap; 
	}


	private static String addWeek(String week){
		String theYear = week.split(":")[0];
		String theWeek = week.split(":")[1]; 

		if(theWeek.equals("52")){
			theYear = "" + (1 + (Integer.parseInt(theYear)));
			theWeek = "" + 1;
		}
		else{
			theWeek = "" + (1 + (Integer.parseInt(theWeek))); 
		}

		String retString = theYear + ":" + theWeek;
		return theYear + ":" + theWeek;
	}

	public static String makeKey(String year, String week){
		return year + ":" + week; 
	}
	
	
	public static DateTime findStartDate(HashMap<String, ArrayList<WordParser>> theMap){
		
//		String earliestKey = "999";
//		for(String key : theMap.keySet()){
//			if(key.compareToIgnoreCase(earliestKey) < 0){
//				earliestKey = key;
//			}
//		}
//		
//		System.out.println(earliestKey);
//		
//		
//		//march first.
		Calendar startDate = Calendar.getInstance();
		startDate.set(2010, 3, 1);
		
		return (new DateTime(startDate)); //liestKey;
	}
	
	public static DateTime findEndDate(HashMap<String, ArrayList<WordParser>> theMap){
//		
//		String latestKey = "0";
//		for(String key : theMap.keySet()){
//			if(key.compareToIgnoreCase(latestKey) > 0){
//				latestKey = key;
//			}
//		}
//		
//		System.out.println(latestKey);
		
		return (new DateTime());
	}
	
	public static String parseDate(DateTime dt){
		return ("" + dt.getYear() + dt.getWeekOfWeekyear()); 
		
	}

	public static void main(String[] args) {
		
//		DateTime whatever = findStartDate(null);
//		DateTime eh = findEndDate(null); 
//		
//		//year, month, date, hour, minute
//		Calendar startCal = Calendar.getInstance();
//		startCal.set(2011, 1, 30);
//
//		Calendar endCal = Calendar.getInstance();
//		endCal.set(2012, 1, 30); 
//		
//		
//		System.out.println("" + internshipNumbers.length + ":" + careerNumbers.length + ":" + organization.length);
//		
//		double[] percents = getYearPercents("internship"); 
//		for(double d : percents){
//			System.out.println(d);
//		}
		
		String[] ugh = getEmailsFromDate("03/04/2011 to 05/08/2011", "linkedin");
		for(String element : ugh){
			System.out.println(element);
		}

	}
}
